﻿using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections.Generic;



namespace KDG.Sys.Windows
{
    public class RegisteredDocumentIcon
    {
        private static Dictionary<string, Bitmap> _iconHash = new Dictionary<string, Bitmap>();
        private static bool _useHash = true;

        public static bool UseHash
        {
            get { return _useHash; }
            set { _useHash = value; }
        }

        public static Bitmap GetIcon(string fileName)
        {
            Bitmap icon = null;
            string extension = Path.GetExtension(fileName);
            if (!_iconHash.ContainsKey(extension))
            {
                icon = GetIconFromSystem(fileName);
                _iconHash.Add(extension, icon);
            }

            return _iconHash[extension];
        }

        private static Bitmap GetIconFromSystem(string fileName)
        {
            //Getting the small Icon
            ShellFileInfoStructure a_shinfo = new ShellFileInfoStructure();
            SHGetFileInfo(fileName, 0x4000, out a_shinfo,
                (uint)Marshal.SizeOf(a_shinfo), 0x111);
            return Bitmap.FromHicon(a_shinfo.hIcon);
        }
        public static Dictionary<string, Bitmap> IconHash { get { return _iconHash; } }

        #region Import win32
        // SHFILEINFO structure
        [StructLayout(LayoutKind.Sequential)]
        private struct ShellFileInfoStructure
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        [DllImport("shell32.dll")]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes,
            out ShellFileInfoStructure psfi, uint cbSizeFileInfo, uint uFlags);
        #endregion
    }
}